package com.test.diy_annotation_aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect     // 把当前类标识为一个切面
@Component
public class Aop {

    @Before(value = "@annotation(com.test.diy_annotation_aop.TestAnnotation)")
    public void before() {
        System.out.println("--------------前置通知---------------");
    }

    @After(value = "@annotation(com.test.diy_annotation_aop.TestAnnotation)")
    public void after() {
        System.out.println("==============后置通知===============");
    }

    @Around(value = "@annotation(com.test.diy_annotation_aop.TestAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) {
        try {
            System.out.println("环绕通知开始执行");
            Object proceed = joinPoint.proceed();   // 使用到 @TestAnnotation 注解的接口执行
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
            String desc = testAnnotation.desc();
            String value = testAnnotation.value();
            System.out.println(joinPoint.getSignature().getDeclaringTypeName() + "的" + joinPoint.getSignature().getName() + "方法执行完成");
            System.out.println("环绕通知执行结束");
            return proceed;
        } catch (Throwable e) {
            return "系统异常: " + e;
        }
//        System.out.println("环绕通知");
    }

    // 执行顺序
    /*
        环绕通知开始执行
        --------------前置通知---------------
        ==============后置通知===============
        环绕通知执行结束
     */
}
